package com.whfc.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/21 17:14
 */
public class IPUtil {

    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    /**
     * 判断ip是否在cidr网段内
     *
     * @param ip   100.120.199.129
     * @param cidr 100.64.0.0/10
     * @return
     */
    public static boolean checkCIDR(String ip, String cidr) {
        String binaryIp = IPUtil.getBinaryIP(ip);
        String[] cidrArr = cidr.split("/");
        String cidrIp = cidrArr[0];
        int cidrMask = Integer.valueOf(cidrArr[1]);
        String binaryCidrIp = getBinaryIP(cidrIp);
        if (binaryCidrIp == null) {
            return false;
        }
        String binaryHost = binaryIp.substring(0, cidrMask);
        String binaryCidrHost = binaryCidrIp.substring(0, cidrMask);
        return binaryHost.equals(binaryCidrHost);
    }

    /**
     * ip地址转换成二进制字符串
     *
     * @param ip
     * @return
     */
    public static String getBinaryIP(String ip) {
        try {
            String[] decimalArr = ip.split("\\.");
            StringBuffer binaryArr = new StringBuffer();
            for (int i = 0; i < decimalArr.length; i++) {
                String binaryStr = Integer.toString(Integer.valueOf(decimalArr[i], 10), 2);
                for (int j = 0; j < 8 - binaryStr.length(); j++) {
                    binaryArr.append('0');
                }
                binaryArr.append(binaryStr);
            }
            return binaryArr.toString();
        } catch (Exception ex) {
            logger.error("不正确的ip地址");
        }
        return null;
    }

    public static void main(String[] args) {
        String ip = "100.120.199.129";
        String cidr = "100.64.0.0/10";
        System.out.println(checkCIDR(ip, cidr));
    }
}
